//
//  MainViewController.m
//  ZhiHuDaily
//
//  Created by albert on 16/8/14.
//  Copyright © 2016年 albert. All rights reserved.
//

#import "MainViewController.h"
#import "MainTableViewController.h"
#import "MainNavigationController.h"
#import "MeViewController.h"
#import "MyCollectionViewController.h"
#import "MessageViewController.h"
#import "LeftViewController.h"
#import "SettingTableViewController.h"
#import "SectionListViewController.h"
#import "ThemesModel.h"
#import "BaseThemeViewController.h"
#import "DrawerScrollView.h"
//#import "JKTopWindowViewController.h"
#import "JKLoginTool.h"
#import "JKAccountManager.h"
#import "NewsDetailViewController.h"
#import "NetworkingTool.h"
#import "NewsListGetDataModel.h"
#import "NewsListModel.h"

@interface MainViewController () <UIScrollViewDelegate, MeViewControllerDelegate>
/** drawerScrollView */
@property (nonatomic, weak) DrawerScrollView *drawerScrollView;

/** leftVc */
@property (nonatomic, weak) LeftViewController *leftVc;

/** 主页tableVc */
//@property (nonatomic, weak) MainTableViewController *mainTableVc;

/** 主页nav */
@property (nonatomic, weak) MainNavigationController *mainNav;

/** coverBtn */
@property (nonatomic, weak) UIButton *coverBtn;

/** 摇一摇夜间模式是否打开 */
@property (nonatomic, assign) BOOL isShakeCanChangeSkin;

/** 当前皮肤模式 */
@property (nonatomic, copy) NSString *currentSkinModel;

/** drawerScrollView开始拖拽时的x偏移 */
@property (nonatomic, assign) CGFloat beginDragingOffX;
@end

@implementation MainViewController

static CGFloat const animationDuration = 0.5;

// 当前索引
static CGFloat _index = -1;

- (UIButton *)coverBtn{
    if (!_coverBtn) {
        UIButton *coverBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        coverBtn.backgroundColor = [UIColor clearColor];
        coverBtn.frame = CGRectMake(JKScreenW * 3 / 5, 0, JKScreenW * 2 / 5, JKScreenH);
        [coverBtn addTarget:self action:@selector(coverBtnClick) forControlEvents:(UIControlEventTouchUpInside)];
        [self.drawerScrollView addSubview:coverBtn];
        _coverBtn = coverBtn;
    }
    return _coverBtn;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setup];
    
    [self startMonitor];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    [self handle3DTouch];
}

- (void)applicationDidBecomeActive{
    [self handle3DTouch];
}

- (void)handle3DTouch{
    if (!self.jumpTo) return;
    
    if ([self.jumpTo isEqualToString:@"最新日报"]) {
        
        [NewsListGetDataModel loadLatestDatafWithFinishedBlock:^(NSDictionary *dict, NSError *error) {
            if (error || dict == nil) {
                return;
            }
            
            NewsListModel *model = [dict[JKStoryListKey] firstObject];
            
            NewsDetailViewController *detailViewController = [[NewsDetailViewController alloc] init];
            
            detailViewController.storyID = model.ID;
            detailViewController.is3DTouchJump = YES;
            
            [self.mainNav pushViewController:detailViewController animated:YES];
        }];
        
    }else if ([self.jumpTo isEqualToString:@"最新瞎扯"]) {
        NSString *urlStr = @"http://news-at.zhihu.com/api/3/section/2";
        
        [[NetworkingTool sharedNetworkingTool] loadDataWithUrl:urlStr parameters:nil finishedBlock:^(id responseObj, NSError *error) {
            if (error) {
                
                return;
            }
            NSDictionary *dict = [responseObj[@"stories"] firstObject];
            
            NewsDetailViewController *detailViewController = [[NewsDetailViewController alloc] init];
            
            detailViewController.storyID = [dict[@"id"] intValue];
            detailViewController.is3DTouchJump = YES;
            
            [self.mainNav pushViewController:detailViewController animated:YES];
        }];
    }
    
    self.jumpTo = nil;
}

- (void)setup{
    DrawerScrollView *drawerScrollView = [[DrawerScrollView alloc] init];
    drawerScrollView.delegate = self;
    drawerScrollView.frame = self.view.bounds;
    
    drawerScrollView.contentSize = CGSizeMake(self.view.width + JKScreenW * 3 / 5, self.view.height);
    drawerScrollView.contentOffset = CGPointMake(JKScreenW * 3 / 5, 0);
    drawerScrollView.pagingEnabled = YES;
    drawerScrollView.bounces = NO;
    drawerScrollView.showsHorizontalScrollIndicator = NO;
    drawerScrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:drawerScrollView];
    self.drawerScrollView = drawerScrollView;
    
    LeftViewController *leftVc = [[LeftViewController alloc] init];
    [self addChildViewController:leftVc];
    leftVc.view.frame = CGRectMake(0, 0, JKScreenW * 3 / 5, self.view.height);
    [drawerScrollView addSubview:leftVc.view];
    self.leftVc = leftVc;
    
    MainTableViewController *mainTableVc = [[MainTableViewController alloc] init];
    MainNavigationController *mainNav = [[MainNavigationController alloc] initWithRootViewController:mainTableVc];
    __weak typeof(self) weakSelf = self;
    [mainNav setBackBtnBlock:^{
        [weakSelf back];
    }];
    self.mainNav = mainNav;
    [self addChildViewController:mainNav];
    self.mainNav.view.frame = self.view.bounds;
    self.mainNav.view.x = self.leftVc.view.width;
    [self.drawerScrollView insertSubview:mainNav.view belowSubview:self.mainNav.view];
    
    [[UIApplication sharedApplication] setStatusBarStyle:(UIStatusBarStyleLightContent)];
}

- (void)startMonitor{
    __weak typeof(self) weakSelf = self;
    [self.leftVc setIconBtnBlock:^{ // 头像
        _index = -1;
        if (![JKAccountManager sharedmanager].isLogin) {
            [JKLoginTool showLogin];
        }else{
            MeViewController *meVc = [[MeViewController alloc] init];
            meVc.delegate = weakSelf;
            [weakSelf changeMainNavWithViewController:meVc];
        }
    }];
    
    [self.leftVc setCollectionBtnBlock:^{ // 收藏
        MyCollectionViewController *vc = [[MyCollectionViewController alloc] init];
        [weakSelf changeMainNavWithViewController:vc];
        _index = -1;
    }];
    
    [self.leftVc setMessageBtnBlock:^{ // 消息
        MessageViewController *msgVc = [[MessageViewController alloc] init];
        [weakSelf changeMainNavWithViewController:msgVc];
        _index = -1;
        
    }];
    
    [self.leftVc setSettingBtnBlock:^{ // 设置
        [weakSelf changeToSetting];
    }];
    
    [self.leftVc setCellSelectedBlock:^(ThemesModel *model, NSInteger index) {
        if (_index == index) {
            [weakSelf coverBtnClick];
            return;
        }
        
        _index = index;
        
        if (index == 0) { // 首页
            MainTableViewController *mainTableVc = [[MainTableViewController alloc] init];
            [weakSelf changeMainNavWithViewController:mainTableVc];
            
        }else if (index == 1){ // 专栏
            SectionListViewController *sectionListVc = [[SectionListViewController alloc] init];
            [weakSelf changeMainNavWithViewController:sectionListVc];
            
        }else{ // 其它主题
            BaseThemeViewController *themeVc = [[BaseThemeViewController alloc] init];
            themeVc.themeModel = model;
            
            [weakSelf changeMainNavWithViewController:themeVc];
        }
    }];
}

// 切换控制器
- (void)changeMainNavWithViewController:(UIViewController *)viewController{
    __weak typeof(self) weakSelf = self;
    MainNavigationController *mainNav = [[MainNavigationController alloc] initWithRootViewController:viewController];
    [mainNav setBackBtnBlock:^{
        [weakSelf back];
    }];
    mainNav.view.frame = weakSelf.view.bounds;
    mainNav.view.x = weakSelf.leftVc.view.width;
    [weakSelf addChildViewController:mainNav];
    [weakSelf.drawerScrollView insertSubview:mainNav.view belowSubview:weakSelf.mainNav.view];
    
    [UIView animateWithDuration:animationDuration animations:^{
        weakSelf.mainNav.view.alpha = 0;
        weakSelf.drawerScrollView.contentOffset = CGPointMake(JKScreenW * 3 / 5, 0);
        
    } completion:^(BOOL finished) {
        [weakSelf.mainNav.view removeFromSuperview];
        [weakSelf.mainNav removeFromParentViewController];
        weakSelf.mainNav = mainNav;
    }];
}

- (void)changeToSetting{
    _index = -1;
    __weak typeof(self) weakSelf = self;
    MainNavigationController *settingNav = [UIStoryboard storyboardWithName:NSStringFromClass([SettingTableViewController class]) bundle:nil].instantiateInitialViewController;
    
    [settingNav setBackBtnBlock:^{
        [weakSelf back];
    }];
    
    [weakSelf addChildViewController:settingNav];
    [weakSelf.drawerScrollView insertSubview:settingNav.view belowSubview:weakSelf.mainNav.view];
    settingNav.view.frame = weakSelf.view.bounds;
    settingNav.view.x = weakSelf.leftVc.view.width;
    
    [UIView animateWithDuration:animationDuration animations:^{
        weakSelf.mainNav.view.alpha = 0;
        weakSelf.drawerScrollView.contentOffset = CGPointMake(JKScreenW * 3 / 5, 0);
        
    } completion:^(BOOL finished) {
        [weakSelf.mainNav.view removeFromSuperview];
        [weakSelf.mainNav removeFromParentViewController];
        weakSelf.mainNav = settingNav;
    }];
}

- (void)back{
    [self.leftVc updateUserIconAndName];
    
    [UIView animateWithDuration:animationDuration animations:^{
        self.drawerScrollView.contentOffset = CGPointMake(0, 0);
    }];
}

- (void)coverBtnClick{
    [UIView animateWithDuration:animationDuration animations:^{
        self.drawerScrollView.contentOffset = CGPointMake(JKScreenW * 3 / 5, 0);
        self.coverBtn.hidden = YES;
        [self.coverBtn removeFromSuperview];
        self.coverBtn = nil;
    }];
}

#pragma mark - <UIScrollViewDelegate>
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.x == 0) {
        
        self.coverBtn.hidden = NO;
    }else{
        self.coverBtn.hidden = YES;
        [self.coverBtn removeFromSuperview];
        self.coverBtn = nil;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.x == 0) {
        [self.leftVc updateUserIconAndName];
    }
}

- (void)meViewControllerDidClickLogout:(MeViewController *)meViewController{
    [self changeToSetting];
}

// 摇一摇
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    if (motion != UIEventSubtypeMotionShake) return;
    
    self.isShakeCanChangeSkin = [[NSUserDefaults standardUserDefaults] boolForKey:JKIsShakeCanChangeSkinKey];
    
    if (self.isShakeCanChangeSkin == NO) return;
    
    self.currentSkinModel = [[NSUserDefaults standardUserDefaults] objectForKey:JKCurrentSkinModelKey];
    
    if ([self.currentSkinModel isEqualToString:JKDaySkinModelValue]) {//当前为日间模式，切换至夜间模式
        [[NSUserDefaults standardUserDefaults] setObject:JKNightSkinModelValue forKey:JKCurrentSkinModelKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
    } else {//当前为夜间模式，切换至日间模式
        [[NSUserDefaults standardUserDefaults] setObject:JKDaySkinModelValue forKey:JKCurrentSkinModelKey];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:JKDeviceDidShakeNotification object:self];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
